package main

import (
	"flag"
	"fmt"
	config "golang-blog/conf"
	"golang-blog/helper"
	"golang-blog/infrastructure/cache"
	"golang-blog/infrastructure/log"
	"golang-blog/models"
	"golang-blog/routes"
	"path"
	"path/filepath"
	"strings"

	"github.com/fvbock/endless"
)

func init() {
	dir, err := helper.GetAppDirectory()
	if err != nil {
		panic(err)
	}
	var cfg string
	// 读取参数
	// 当文件编译后的路径
	flag.StringVar(&cfg, "config", path.Join(dir, "./conf/conf.yaml"), "config file path")
	flag.Parse()

	// 初始化配置
	initConfig(cfg)

	// 初始化日志
	logLevel := config.Viper().GetString("logLevel")
	initLog(logLevel, path.Join(dir, "./logs"))

	// 初始化数据库
	tables := []interface{}{
		&models.Article{},
		&models.Category{},
		&models.PostTag{},
		&models.Tag{},
		&models.User{},
	}
	models.DBMigration(tables)

	// 初始化缓存
	cache.InitCache()

}
func main() {
	// 查看配置是否加载成功
	// map[dbname:blog host:localhost passwd:root port:33306 user:root]
	fmt.Println(config.Viper().Get("db.mysql"))
	// trace
	fmt.Println(config.Viper().Get("logLevel"))

	// 路由设置
	r := routes.SetupRouter()
	listenPort := 30082
	server := endless.NewServer(fmt.Sprintf(":%d", listenPort), r)

	//// save pid file
	//server.BeforeBegin = func(add string) {
	//	pid := syscall.Getpid()
	//	fmt.Println("Actual pid is ", pid)
	//	pidFile := "server.pid"
	//	if utils.CheckFileIsExist(pidFile) {
	//		os.Remove(pidFile)
	//	}
	//	if err := ioutil.WriteFile(pidFile, []byte(fmt.Sprintf("%d", pid)), 0666); err != nil {
	//		fmt.Printf("Api server write pid file failed! err:%v", err)
	//	}
	//}

	err := server.ListenAndServe()
	if err != nil {
		if strings.Contains(err.Error(), "use of closed network connection") {
			fmt.Println(err)
		} else {
			fmt.Printf("Api server start failed! err:%v", err)
			panic(err)
		}
		return
	}
}

func initConfig(cfgPath string) {
	fmt.Println(cfgPath)
	fullPath, err := filepath.Abs(cfgPath)
	if err != nil {
		panic(err)
	}
	config.Init(fullPath)
}

func initLog(logLevel string, logDir string) {
	// 设置日志文件名
	lf, err := log.LogFile(logDir, "")
	if err != nil {
		panic(err)
	}
	log.Init(logLevel, lf)
}
